package com.shiwenping.reply.view;

import android.app.Activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.shiwenping.reply.R;
import com.shiwenping.reply.adapter.AbstractListAdapter;
import com.shiwenping.reply.adapter.BaseViewHolder;
import com.shiwenping.reply.databinding.PopwindowCateItemLayoutBinding;
import com.shiwenping.reply.databinding.PopwindowCateLayoutBinding;
import com.shiwenping.reply.net.ApiManager;
import com.shiwenping.reply.net.service.AllService;
import com.shiwenping.reply.recycle.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 *  分类
 * @author haichecker
 * @date 17-11-11
 */

public class CateDialog {
    //数据源
    private List<String> data;
    //布局对象
    private PopwindowCateLayoutBinding popwindowCateLayoutBinding;

    private PopupWindow popupWindow;

    private Context mContext;

    private Adapter adapter;

    private OnSelectCateListener onSelectCateListener;

    //是否为文件分类
    private boolean isFile;
    public CateDialog(Context mContext,boolean isFile)
    {
        this.isFile = isFile;
        this.mContext = mContext;
        popupWindow = new PopupWindow(mContext);
        View view = LayoutInflater.from(mContext)
                .inflate(R.layout.popwindow_cate_layout,null,false);
        popwindowCateLayoutBinding = DataBindingUtil.bind(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(mContext.getResources().getDisplayMetrics().heightPixels / 3);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setTouchable(true);
        adapter = new Adapter(1,mContext, ContextCompat.getColor(mContext,R.color.color_line));
        VirtualLayoutManager manager = new VirtualLayoutManager(mContext);
        popwindowCateLayoutBinding.recycler.setLayoutManager(manager);
        DelegateAdapter d = new DelegateAdapter(manager);
        d.addAdapter(adapter);
        popwindowCateLayoutBinding.recycler.setAdapter(d);
        popwindowCateLayoutBinding.recycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onClick(RecyclerView.ViewHolder viewHolder, int position) {
                if (onSelectCateListener != null) {
                    onSelectCateListener.onSelect(data.get(position));
                }
                hide();
            }
        });
        RxView.clicks(popwindowCateLayoutBinding.load)
                .subscribe(o -> getData());

        popupWindow.setContentView(view);
    }

    public boolean isShowing()
    {
        return popupWindow.isShowing();
    }

    /**
     * 获取数据
     */
    private void getData()
    {
       AllService allService = ApiManager.retrofit(mContext)
                .create(AllService.class);

        (isFile ? allService.getFileTags() : allService.getFagTags())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(() ->{
                    popwindowCateLayoutBinding.load.setVisibility(View.VISIBLE);
                    popwindowCateLayoutBinding.message.setText(mContext.getString(R.string.data_loading));
                    popwindowCateLayoutBinding.recycler.setVisibility(View.GONE);
                    popwindowCateLayoutBinding.progress.setVisibility(View.VISIBLE);
                })
                .subscribe(listBaseHttpResult -> {
                    if (listBaseHttpResult.isSuccess())
                    {
                        this.data = listBaseHttpResult.getData();
                        popwindowCateLayoutBinding.load.setVisibility(View.GONE);
                        popwindowCateLayoutBinding.recycler.setVisibility(View.VISIBLE);
                        adapter.notifyDataSetChanged();
                        popwindowCateLayoutBinding.recycler.getAdapter().notifyDataSetChanged();
                    }else {
                        popwindowCateLayoutBinding.load.setVisibility(View.VISIBLE);
                        popwindowCateLayoutBinding.progress.setVisibility(View.GONE);
                        popwindowCateLayoutBinding.message.setText(mContext.getString(R.string.data_load_err_click_ref));
                        popwindowCateLayoutBinding.recycler.setVisibility(View.GONE);
                    }
                },throwable -> {
                    popwindowCateLayoutBinding.load.setVisibility(View.VISIBLE);
                    popwindowCateLayoutBinding.progress.setVisibility(View.GONE);
                    popwindowCateLayoutBinding.message.setText(mContext.getString(R.string.data_load_err_click_ref));
                    popwindowCateLayoutBinding.recycler.setVisibility(View.GONE);
                });

    }

    /**
     * 选择回调
     */
    public static interface OnSelectCateListener{
        /**
         * 选择成功
         * @param cateName  返回文件分类
         */
        void onSelect(String cateName);
    }

    public void hide()
    {
        popupWindow.dismiss();
    }

    public void setOnSelectCateListener(OnSelectCateListener onSelectCateListener) {
        this.onSelectCateListener = onSelectCateListener;
    }

    public void show(View view)
    {
        popupWindow.showAsDropDown(view);
        popupWindow.setAnimationStyle(R.style.cate_pop_window);
        popupWindow.update();
        if (data == null || data.size() == 0)
        {
            getData();
        }
    }

    private class Adapter extends AbstractListAdapter<BaseViewHolder<PopwindowCateItemLayoutBinding>>{

        public Adapter(int dividerHeight, Context context, int bgColor) {
            super(dividerHeight, context, bgColor);
        }

        @Override
        public BaseViewHolder<PopwindowCateItemLayoutBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
            return new BaseViewHolder<>(inflater.inflate(R.layout.popwindow_cate_item_layout,parent,false));
        }

        @Override
        public void onBindViewHolder(BaseViewHolder<PopwindowCateItemLayoutBinding> holder, int position) {
            holder.databinding.text.setText(data.get(position));
            Log.d("HaiChecker",data.get(position));

        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }
    }
    private void setBackgroundAlpha(float bgAlpha){
        WindowManager.LayoutParams layoutParams = ((Activity)mContext).getWindow().getAttributes();
        layoutParams.alpha = bgAlpha; //0.0-1.0
        ((Activity)mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//多加这一句，问题就解决了！这句的官方文档解释是：让窗口背景后面的任何东西变暗
        ((Activity)mContext).getWindow().setAttributes(layoutParams);
    }
}
